# -*- coding: utf-8 -*-


import traceback
import pymysql
import aiomysql
# from apps.log import logging
import  logging

class CustomSQL(object):
    def __init__(self, setting):
        self.setting = setting
        self.pool = None

    async def create_pool(self):
        if not self.pool:
            try:
                self.pool = await aiomysql.create_pool(minsize=1, maxsize=50, **self.setting)
                logging.info('database connection')
                return self.pool
            except:
                logging.error('connectDatabase failed')
            return None

    async def execute(self, sql, params=None):
        logging.info(sql)
        result = False
        if not self.pool:
            await self.create_pool()
        async with self.pool.acquire() as conn:
            async with conn.cursor(aiomysql.DictCursor) as cur:
                try:
                    await cur.execute(sql, params)
                    result = True
                except:
                    await conn.rollback()
                    logging.error(traceback.format_exc())
                await conn.commit()
                await self.pool.clear()
        return result

    async def fetchall(self, sql, params=None):
        logging.info(sql)
        result = None
        # sql = pymysql.escape_string(sql)
        if not self.pool:
            await self.create_pool()
        # logging.info('当前数据库池大小：' + str(self.pool.size))
        # logging.info('当前数据库池剩余大小：' + str(self.pool.freesize))

        async with self.pool.acquire() as conn:
            async with conn.cursor(aiomysql.DictCursor) as cur:
                try:
                    await cur.execute(sql, params)
                    result = await cur.fetchall()
                except:
                    await conn.rollback()
                    logging.error(traceback.format_exc())
                await conn.commit()
                await self.pool.clear()
        return result

    async def fetchone(self, sql, params=None):
        logging.info(sql)
        result = None
        if not self.pool:
            await self.create_pool()
        async with self.pool.acquire() as conn:
            async with conn.cursor(aiomysql.DictCursor) as cur:
                try:
                    await cur.execute(sql, params)
                    result = await cur.fetchone()
                except:
                    await conn.rollback()
                    logging.error(traceback.format_exc())
                await conn.commit()
                await self.pool.clear()
        return result
